package echat.future.cn.echat.message;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.easeui.widget.EaseConversationList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import echat.future.cn.echat.R;
import echat.future.cn.echat.home.ChatActivity;
import echat.future.cn.echat.message.activity.AppointmentActivity;
import echat.future.cn.echat.message.activity.EbiActivity;
import echat.future.cn.echat.message.activity.MyCallActivity;
import echat.future.cn.echat.message.adapter.MessageAdapter;
import echat.future.cn.echat.my.utils.UserHelper;
import lumingweihua.future.cn.baselibgxh.base.BaseFragment;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;

/**
 * Created by Administrator on 2018/8/9.
 */

public class MessageFragment extends BaseFragment {

    private RecyclerView rv;
    private MessageAdapter mAdapter;

    private final static int MSG_REFRESH = 2;
    protected boolean hidden;
    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    protected EaseConversationList conversationListView;
    protected FrameLayout errorItemContainer;

    protected boolean isConflict;

    private EaseUI easeUI;

    private Map<String, UserData> mUserMap = new HashMap<>();
    private List<String> mMobileList = new ArrayList<>();

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_message, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        initAdapter();

        findView(R.id.ll_ebi).setOnClickListener(this);
        findView(R.id.ll_mycall).setOnClickListener(this);
        findView(R.id.ll_appointment).setOnClickListener(this);

        conversationListView = (EaseConversationList) getView().findViewById(com.hyphenate.easeui.R.id.list);

        set2UpView();

//        EMClient.getInstance().groupManager().loadAllGroups();
//        EMClient.getInstance().chatManager().loadAllConversations();
//
//        mConversationList = new ArrayList<>();
//        mConversationList.addAll(loadConversationList());

    }

    protected void set2UpView() {
        setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();

                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    UserData user = mUserMap.get(username);
                    // start chat acitivity
                    startActivity(new Intent(getActivity(), ChatActivity.class)
                            .putExtra("id", username)
                            .putExtra("avatar", user == null ? "" : user.avatar)
                            .putExtra("username", user == null ? "" : user.username));
//                    Intent intent = new Intent(getActivity(), ChatActivity.class);
//                    if (conversation.isGroup()) {
//                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
//                            // it's group chat
//                            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_CHATROOM);
//                        } else {
//                            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
//                        }
//
//                    }
//                    // it's single chat
//                    intent.putExtra(EaseConstant.EXTRA_USER_ID, username);
//                    startActivity(intent);
                }
            }
        });
        setUpView();
    }

    private void setUpView() {
        conversationList.addAll(loadConversationList());


        conversationListView.init(conversationList);

        Log.e("TAG", "消息列表 = " + conversationList.size());

//        if (conversationList.size() == 0) {
//            Toast.makeText(context, "暂无聊天", Toast.LENGTH_SHORT).show();
//        }

        if (listItemClickListener != null) {
            conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    EMConversation conversation = conversationListView.getItem(position);
                    listItemClickListener.onListItemClicked(conversation);
                }
            });
        }

        EMClient.getInstance().addConnectionListener(connectionListener);

        easeUI = EaseUI.getInstance();
        //需要EaseUI库显示用户头像和昵称设置此provider
        easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
                Log.e("TAG", " username=" + username);
                EaseUser easeUser = new EaseUser(username);
                UserData user = mUserMap.get(username);
                if (!mMobileList.contains(username)) {
                    mMobileList.add(username);
                    requestDatas(username, mMobileList.size() - 1);
                }else {
                    if (user != null) {
                        Log.e("TAG", "设置用户信息");
                        easeUser.setAvatar(user.avatar);
                        easeUser.setNickname(user.username);
                    }
                    return easeUser;
                }
                return null;
            }
        });
    }

    private void initAdapter() {
        rv = (RecyclerView) findView(R.id.message_rv);
        mAdapter = new MessageAdapter(getActivity());
        rv.setAdapter(mAdapter);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.ll_ebi:
                startActivity(new Intent(getActivity(), EbiActivity.class));
                break;
            case R.id.ll_mycall:
                startActivity(new Intent(getActivity(), MyCallActivity.class));
                break;
            case R.id.ll_appointment:
                startActivity(new Intent(getActivity(), AppointmentActivity.class));
                break;
        }
    }

    protected EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                handler.sendEmptyMessage(0);
            }
        }

        @Override
        public void onConnected() {
            handler.sendEmptyMessage(1);
        }
    };
    private EaseConversationListFragment.EaseConversationListItemClickListener listItemClickListener;

    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_REFRESH: {
                    conversationList.clear();
                    conversationList.addAll(loadConversationList());
                    conversationListView.refresh();
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * refresh ui
     */
    public void refresh() {
        if (handler != null && !handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    /**
     * load conversation list
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        refresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (isConflict) {
            outState.putBoolean("isConflict", true);
        }
    }

    public interface EaseConversationListItemClickListener {
        /**
         * click event for conversation list
         *
         * @param conversation -- clicked item
         */
        void onListItemClicked(EMConversation conversation);
    }

    /**
     * set conversation list item click listener
     *
     * @param listItemClickListener
     */
    public void setConversationListItemClickListener(EaseConversationListFragment.EaseConversationListItemClickListener listItemClickListener) {
        this.listItemClickListener = listItemClickListener;
    }

    private synchronized void requestDatas(String account, int i) {
        BeanRequest<UserData, MamaHaoServerError> req = new BeanRequest<>(
                context,
                "/api/user/get_user_info_by_mobile",
                this,
                UserData.class);

        req.setParam("token", UserHelper.getToken());
        req.setParam("mobile", account);

        baseActivity.addRequestQueue(req, i);
    }

    @Override
    protected synchronized void onResponseSuccess(ReqTag tag, Object data) {
        super.onResponseSuccess(tag, data);
        String mobile = mMobileList.get(tag.getReqId());
        UserData ud = (UserData) data;
        mUserMap.put(mobile, ud);
        refresh();
        Log.e("TAG", "onResponseSuccess");
//        if (tag.getReqId() == 1) {
//            UserData ud = (UserData) data;
//            mUserMap.put(ud.username, ud);
//        }
    }

    class UserData {
        String avatar;//: "http://img4.imgtn.bdimg.com/it/u=4099656746,186489158&fm=15&gp=0.jpg",
        String username;//: "xhq",
        String level;//: "1",
        String auth_status;//: 1
        String anchor_id;//: 1
    }

}